package org.wishwork.api.express.query;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.express.query.response.ExpressQueryResponse;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 发货信息查询
 * @author: WangYX
 * @create: 2022-04-13 09:19
 * @Version: 1.0.0
 **/

public class ExpressQueryApi extends Api<List<ExpressQueryResponse>, ExpressQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(ExpressQueryApi.class);

    private Context context;

    public ExpressQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(ExpressQueryRequest expressQueryRequest) throws Exception {
        String url = "/open/logistic/query";
        Map<String, Object> params = new HashMap<>();
        if (expressQueryRequest.getShopId() != null) {
            params.put("shop_id", expressQueryRequest.getShopId());
        }
        if (expressQueryRequest.getDateType() != null) {
            params.put("date_type", expressQueryRequest.getDateType());
        }
        if (expressQueryRequest.getSoIds() != null && expressQueryRequest.getSoIds().size() > 0) {
            params.put("so_ids", expressQueryRequest.getSoIds());
        }
        return HttpHelper.sendRequest(expressQueryRequest, params, url);
    }

    @Override
    protected List<ExpressQueryResponse> process(JSONObject data, ExpressQueryRequest expressQueryRequest) throws Exception {
        JSONArray orders = data.getJSONArray("orders");
        List<ExpressQueryResponse> expressQueryResponses = orders.toJavaList(ExpressQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = expressQueryRequest.getPageIndex();
            ExpressQueryRequest build = expressQueryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<ExpressQueryResponse> business = business(build);
            expressQueryResponses.addAll(business);
        }
        return expressQueryResponses;
    }
}
